import React, { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {
  Box,
  Typography,
  Paper,
  Button,
  Chip,
  List,
  ListItem,
  ListItemText,
  Divider,
  Alert,
  CircularProgress,
  Tab,
  Tabs,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Tooltip,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
} from '@mui/material';
import {
  ArrowBack as BackIcon,
  PlayArrow as StartIcon,
  Stop as StopIcon,
  PowerSettingsNew as ForceStopIcon,
  Refresh as RebootIcon,
  Pause as SuspendIcon,
  PlayCircle as ResumeIcon,
  Computer as ConsoleIcon,
  Code as XmlIcon,
} from '@mui/icons-material';
import { useConnectionStore } from '../../stores/connectionStore';
import { useDomainStore } from '../../stores/domainStore';
import { DomainState } from '../../types/api';
import type { DomainOperation } from '../../types/api';
import domainService from '../../services/domains';

interface TabPanelProps {
  children?: React.ReactNode;
  index: number;
  value: number;
}

function TabPanel(props: TabPanelProps) {
  const { children, value, index, ...other } = props;
  return (
    <div
      role="tabpanel"
      hidden={value !== index}
      id={`tabpanel-${index}`}
      aria-labelledby={`tab-${index}`}
      {...other}
    >
      {value === index && <Box sx={{ p: 3 }}>{children}</Box>}
    </div>
  );
}

const DomainDetail: React.FC = () => {
  const { name } = useParams<{ name: string }>();
  const navigate = useNavigate();
  const currentConnection = useConnectionStore(state => state.currentConnection);
  const { 
    currentDomain, 
    getDomainDetail, 
    performDomainOperation, 
    loading, 
    error, 
    clearError 
  } = useDomainStore();
  
  const [tabValue, setTabValue] = useState(0);
  const [operationLoading, setOperationLoading] = useState<string | null>(null);
  const [xmlDialogOpen, setXmlDialogOpen] = useState(false);
  const [xmlContent, setXmlContent] = useState('');
  const [stats, setStats] = useState<any>(null);
  const [statsLoading, setStatsLoading] = useState(false);

  // 获取虚拟机详情
  useEffect(() => {
    if (currentConnection && name) {
      getDomainDetail(currentConnection, name);
    }
  }, [currentConnection, name, getDomainDetail]);

  // 获取统计信息
  useEffect(() => {
    if (currentConnection && name && tabValue === 1) {
      fetchStats();
    }
  }, [currentConnection, name, tabValue]);

  // 清除错误
  useEffect(() => {
    if (error) {
      const timer = setTimeout(() => clearError(), 5000);
      return () => clearTimeout(timer);
    }
  }, [error, clearError]);

  const fetchStats = async () => {
    if (!currentConnection || !name) return;
    
    setStatsLoading(true);
    try {
      const domainStats = await domainService.getDomainStats(currentConnection, name);
      setStats(domainStats);
    } catch (error) {
      console.error('获取统计信息失败:', error);
    } finally {
      setStatsLoading(false);
    }
  };

  const fetchXML = async () => {
    if (!currentConnection || !name) return;
    
    try {
      const xml = await domainService.getDomainXML(currentConnection, name);
      setXmlContent(xml);
      setXmlDialogOpen(true);
    } catch (error) {
      console.error('获取XML配置失败:', error);
    }
  };

  const handleOperation = async (operation: DomainOperation) => {
    if (!currentConnection || !name) return;
    
    setOperationLoading(operation);
    try {
      await performDomainOperation(currentConnection, name, operation);
    } catch (error) {
      console.error(`虚拟机操作 ${operation} 失败:`, error);
    } finally {
      setOperationLoading(null);
    }
  };

  const getStateColor = (state: string) => {
    switch (state) {
      case DomainState.RUNNING:
        return 'success';
      case DomainState.SHUTOFF:
        return 'default';
      case DomainState.PAUSED:
        return 'warning';
      case DomainState.SUSPENDED:
        return 'info';
      case DomainState.CRASHED:
        return 'error';
      default:
        return 'default';
    }
  };

  const getStateText = (state: string) => {
    switch (state) {
      case DomainState.RUNNING:
        return '运行中';
      case DomainState.SHUTOFF:
        return '已关机';
      case DomainState.PAUSED:
        return '已暂停';
      case DomainState.SUSPENDED:
        return '已挂起';
      case DomainState.CRASHED:
        return '已崩溃';
      default:
        return '未知';
    }
  };

  const isOperationEnabled = (operation: DomainOperation) => {
    if (!currentDomain) return false;
    
    switch (operation) {
      case 'start':
        return currentDomain.state === DomainState.SHUTOFF || currentDomain.state === DomainState.SUSPENDED;
      case 'shutdown':
      case 'force-stop':
      case 'suspend':
        return currentDomain.state === DomainState.RUNNING;
      case 'reboot':
        return currentDomain.state === DomainState.RUNNING;
      case 'resume':
        return currentDomain.state === DomainState.PAUSED;
      default:
        return false;
    }
  };

  if (!currentConnection) {
    return (
      <Box>
        <Typography variant="h4" component="h1" gutterBottom fontWeight="bold">
          虚拟机详情
        </Typography>
        <Alert severity="warning">
          请先选择一个连接
        </Alert>
      </Box>
    );
  }

  if (loading && !currentDomain) {
    return (
      <Box display="flex" justifyContent="center" alignItems="center" minHeight="400px">
        <CircularProgress />
      </Box>
    );
  }

  if (!currentDomain) {
    return (
      <Box>
        <Typography variant="h4" component="h1" gutterBottom fontWeight="bold">
          虚拟机详情
        </Typography>
        <Alert severity="error">
          未找到虚拟机 "{name}"
        </Alert>
      </Box>
    );
  }

  return (
    <Box>
      <Box display="flex" justifyContent="space-between" alignItems="center" mb={3}>
        <Box display="flex" alignItems="center">
          <Button onClick={() => navigate('/domains')} sx={{ mr: 1, minWidth: 'auto' }}>
            <BackIcon />
          </Button>
          <Typography variant="h4" component="h1" fontWeight="bold">
            虚拟机详情: {currentDomain.name}
          </Typography>
        </Box>
        
        <Box display="flex" gap={1}>
          {/* 启动 */}
          <Tooltip title="启动">
            <span>
              <Button
                variant="outlined"
                size="small"
                onClick={() => handleOperation('start')}
                disabled={!isOperationEnabled('start') || operationLoading === 'start'}
                startIcon={operationLoading === 'start' ? <CircularProgress size={16} /> : <StartIcon />}
              >
                启动
              </Button>
            </span>
          </Tooltip>

          {/* 关机 */}
          <Tooltip title="关机">
            <span>
              <Button
                variant="outlined"
                size="small"
                onClick={() => handleOperation('shutdown')}
                disabled={!isOperationEnabled('shutdown') || operationLoading === 'shutdown'}
                startIcon={operationLoading === 'shutdown' ? <CircularProgress size={16} /> : <StopIcon />}
              >
                关机
              </Button>
            </span>
          </Tooltip>

          {/* 强制停止 */}
          <Tooltip title="强制停止">
            <span>
              <Button
                variant="outlined"
                size="small"
                color="error"
                onClick={() => handleOperation('force-stop')}
                disabled={!isOperationEnabled('force-stop') || operationLoading === 'force-stop'}
                startIcon={operationLoading === 'force-stop' ? <CircularProgress size={16} /> : <ForceStopIcon />}
              >
                强制停止
              </Button>
            </span>
          </Tooltip>

          {/* 重启 */}
          <Tooltip title="重启">
            <span>
              <Button
                variant="outlined"
                size="small"
                onClick={() => handleOperation('reboot')}
                disabled={!isOperationEnabled('reboot') || operationLoading === 'reboot'}
                startIcon={operationLoading === 'reboot' ? <CircularProgress size={16} /> : <RebootIcon />}
              >
                重启
              </Button>
            </span>
          </Tooltip>

          {/* 暂停 */}
          <Tooltip title="暂停">
            <span>
              <Button
                variant="outlined"
                size="small"
                onClick={() => handleOperation('suspend')}
                disabled={!isOperationEnabled('suspend') || operationLoading === 'suspend'}
                startIcon={operationLoading === 'suspend' ? <CircularProgress size={16} /> : <SuspendIcon />}
              >
                暂停
              </Button>
            </span>
          </Tooltip>

          {/* 恢复 */}
          <Tooltip title="恢复">
            <span>
              <Button
                variant="outlined"
                size="small"
                onClick={() => handleOperation('resume')}
                disabled={!isOperationEnabled('resume') || operationLoading === 'resume'}
                startIcon={operationLoading === 'resume' ? <CircularProgress size={16} /> : <ResumeIcon />}
              >
                恢复
              </Button>
            </span>
          </Tooltip>

          {/* 控制台 */}
          <Tooltip title="控制台">
            <span>
              <Button
                variant="outlined"
                size="small"
                onClick={() => navigate(`/domains/${name}/console`)}
                disabled={currentDomain.state !== DomainState.RUNNING}
                startIcon={<ConsoleIcon />}
              >
                控制台
              </Button>
            </span>
          </Tooltip>

          {/* XML配置 */}
          <Tooltip title="查看XML配置">
            <Button
              variant="outlined"
              size="small"
              onClick={fetchXML}
              startIcon={<XmlIcon />}
            >
              XML
            </Button>
          </Tooltip>
        </Box>
      </Box>

      {error && (
        <Alert severity="error" sx={{ mb: 2 }} onClose={clearError}>
          {error}
        </Alert>
      )}

      <Paper sx={{ mb: 3 }}>
        <Box sx={{ borderBottom: 1, borderColor: 'divider' }}>
          <Tabs value={tabValue} onChange={(_e, newValue) => setTabValue(newValue)}>
            <Tab label="基本信息" />
            <Tab label="资源统计" />
            <Tab label="配置详情" />
          </Tabs>
        </Box>

        <TabPanel value={tabValue} index={0}>
          <Box sx={{ display: 'grid', gridTemplateColumns: { xs: '1fr', md: '1fr 1fr' }, gap: 3 }}>
            <Box>
              <List>
                <ListItem>
                  <ListItemText
                    primary="名称"
                    secondary={currentDomain.name}
                  />
                </ListItem>
                <Divider />
                <ListItem>
                  <ListItemText
                    primary="UUID"
                    secondary={currentDomain.uuid}
                  />
                </ListItem>
                <Divider />
                <ListItem>
                  <ListItemText
                    primary="状态"
                    secondary={
                      <Chip
                        label={getStateText(currentDomain.state)}
                        color={getStateColor(currentDomain.state)}
                        size="small"
                      />
                    }
                  />
                </ListItem>
                <Divider />
                <ListItem>
                  <ListItemText
                    primary="vCPU数量"
                    secondary={`${currentDomain.vcpus} 核心`}
                  />
                </ListItem>
                <Divider />
                <ListItem>
                  <ListItemText
                    primary="内存"
                    secondary={`${Math.round(currentDomain.memory / 1024)} GB / ${Math.round(currentDomain.max_memory / 1024)} GB`}
                  />
                </ListItem>
              </List>
            </Box>
            <Box>
              <List>
                <ListItem>
                  <ListItemText
                    primary="CPU时间"
                    secondary={`${(currentDomain.cpu_time / 1e9).toFixed(2)} 秒`}
                  />
                </ListItem>
                <Divider />
                <ListItem>
                  <ListItemText
                    primary="连接"
                    secondary={currentConnection}
                  />
                </ListItem>
                <Divider />
                <ListItem>
                  <ListItemText
                    primary="最后更新"
                    secondary={new Date().toLocaleString()}
                  />
                </ListItem>
              </List>
            </Box>
          </Box>
        </TabPanel>

        <TabPanel value={tabValue} index={1}>
          {statsLoading ? (
            <Box display="flex" justifyContent="center" p={3}>
              <CircularProgress />
            </Box>
          ) : stats ? (
            <TableContainer>
              <Table>
                <TableHead>
                  <TableRow>
                    <TableCell>指标</TableCell>
                    <TableCell align="right">当前值</TableCell>
                    <TableCell align="right">峰值</TableCell>
                    <TableCell align="right">平均值</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  <TableRow>
                    <TableCell>CPU使用率</TableCell>
                    <TableCell align="right">{stats.cpu?.current || 0}%</TableCell>
                    <TableCell align="right">{stats.cpu?.peak || 0}%</TableCell>
                    <TableCell align="right">{stats.cpu?.average || 0}%</TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell>内存使用率</TableCell>
                    <TableCell align="right">{stats.memory?.current || 0}%</TableCell>
                    <TableCell align="right">{stats.memory?.peak || 0}%</TableCell>
                    <TableCell align="right">{stats.memory?.average || 0}%</TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell>磁盘I/O</TableCell>
                    <TableCell align="right">{stats.disk?.current || 0} MB/s</TableCell>
                    <TableCell align="right">{stats.disk?.peak || 0} MB/s</TableCell>
                    <TableCell align="right">{stats.disk?.average || 0} MB/s</TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell>网络I/O</TableCell>
                    <TableCell align="right">{stats.network?.current || 0} MB/s</TableCell>
                    <TableCell align="right">{stats.network?.peak || 0} MB/s</TableCell>
                    <TableCell align="right">{stats.network?.average || 0} MB/s</TableCell>
                  </TableRow>
                </TableBody>
              </Table>
            </TableContainer>
          ) : (
            <Alert severity="info">暂无统计信息</Alert>
          )}
        </TabPanel>

        <TabPanel value={tabValue} index={2}>
          <Box sx={{ maxHeight: 400, overflow: 'auto' }}>
            <Typography variant="h6" gutterBottom>
              配置信息
            </Typography>
            <List>
              <ListItem>
                <ListItemText
                  primary="架构"
                  secondary={'x86_64'}
                />
              </ListItem>
              <Divider />
              <ListItem>
                <ListItemText
                  primary="启动模式"
                  secondary={'BIOS'}
                />
              </ListItem>
              <Divider />
              <ListItem>
                <ListItemText
                  primary="磁盘总线"
                  secondary={'virtio'}
                />
              </ListItem>
              <Divider />
              <ListItem>
                <ListItemText
                  primary="网络模式"
                  secondary={'network'}
                />
              </ListItem>
              <Divider />
              <ListItem>
                <ListItemText
                  primary="操作系统类型"
                  secondary={'未指定'}
                />
              </ListItem>
            </List>
          </Box>
        </TabPanel>
      </Paper>

      {/* XML配置对话框 */}
      <Dialog
        open={xmlDialogOpen}
        onClose={() => setXmlDialogOpen(false)}
        maxWidth="md"
        fullWidth
      >
        <DialogTitle>XML配置</DialogTitle>
        <DialogContent>
          <TextField
            multiline
            fullWidth
            rows={20}
            value={xmlContent}
            InputProps={{
              readOnly: true,
            }}
            sx={{ fontFamily: 'monospace', fontSize: '0.875rem' }}
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setXmlDialogOpen(false)}>关闭</Button>
          <Button onClick={() => navigator.clipboard.writeText(xmlContent)}>
            复制到剪贴板
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default DomainDetail;